package com.zyht.common.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import net.coobird.thumbnailator.Thumbnails;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class FileUploadUtil {

	private static Logger logger = LoggerFactory.getLogger(FileUploadUtil.class);
	
	public static String doUpload(String parentFolder, InputStream fileStream, String fileName){
		StringBuffer sb = new StringBuffer();
		String ext = fileName.substring(fileName.indexOf("."));
		sb.append(System.currentTimeMillis()).append(ext);
		String relativePath = sb.toString();
		sb.insert(0, parentFolder);
		File tarFile = new File(sb.toString());
		try{
			FileUtils.copyInputStreamToFile(fileStream, tarFile);
		} catch (IOException e){
			e.printStackTrace();
			logger.error("文件["+tarFile.getAbsolutePath()+"]上传异常："+e.getMessage());
			relativePath = null;
		}finally{
			if(null!=fileStream){
				try{
					fileStream.close();
				} catch (IOException e){
					e.printStackTrace();
				}
			}
		}
		return relativePath;
	}
	
	public static String doUploadImageWithThumb(String parentFolder, InputStream fileStream, String fileName, int w, int h){
		StringBuffer sb = new StringBuffer();
		String ext = fileName.substring(fileName.indexOf("."));
		sb.append(System.currentTimeMillis()).append(ext);
		String relativePath = sb.toString();
		sb.insert(0, parentFolder);
		String thumbPath = getImageThumbPath(sb.toString());
		w = 0==w?120:w;
		h = 0==h?120:h;
		File tarFile = new File(sb.toString());
		try{
			FileUtils.copyInputStreamToFile(fileStream, tarFile);
		} catch (IOException e){
			e.printStackTrace();
			logger.error("文件["+tarFile.getAbsolutePath()+"]上传异常："+e.getMessage());
			relativePath = null;
		}finally{
			if(null!=fileStream){
				try{
					fileStream.close();
				} catch (IOException e){
					e.printStackTrace();
				}
			}
		}
		try{
			Thumbnails.of(tarFile).size(w,h).toFile(thumbPath);
		} catch (IOException e1){
			e1.printStackTrace();
		}
		return relativePath;
	}
	
	/**
	 * <b>作者:</b> zrb<br/>
	 * <b>修改时间：</b>2016年6月8日 - 下午5:28:45<br/>
	 * <b>功能说明：</b>	获取缩略图<br/>
	 * @param imagePath  原图片路径
	 * @return
	 */
	public static String getImageThumbPath(String imagePath){
		if(imagePath!=null){
			int point = imagePath.lastIndexOf(".");
			String path = imagePath.substring(0, point);
			String ext = imagePath.substring(point);
			imagePath = path.concat("_thumb").concat(ext);
		}
		return imagePath;
	}
}
